package com.ljt.yupictureddd.interfaces.controller;

import cn.hutool.core.io.IoUtil;
import com.ljt.yupictureddd.infrastracture.annotation.AuthCheck;
import com.ljt.yupictureddd.infrastracture.common.BaseResponse;
import com.ljt.yupictureddd.infrastracture.common.ResultUtils;
import com.ljt.yupictureddd.domain.user.constant.UserConstant;
import com.ljt.yupictureddd.infrastracture.api.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    CosManager cosManager;

    /**
     * 测试文件上传
     *
     * @param file
     * @return
     */
    @PostMapping
    @AuthCheck(mustRole = "admin")
    public BaseResponse testUploadFile(@RequestPart("file") MultipartFile file) {

        String filePath = "/test/" + file.getOriginalFilename();

        File tempFile = null;
        try {
//            在本地创建临时文件
            tempFile = File.createTempFile(filePath, "");
            file.transferTo(tempFile);
//            上传文件
            cosManager.putObject(filePath, tempFile);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("file upload error, filepath = {}", filePath, e);
            throw new RuntimeException(e);
        } finally {
//            最后一定要删除临时文件
            boolean delete = tempFile.delete();
            if (!delete) {
                log.error("file delete error, filepath = {}", filePath);
            }
        }
    }

    /**
     * 测试文件下载，以流的方式返回
     *
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @GetMapping("/test/download")
    public void testDownloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObject object = cosManager.getObject(filePath);
        try (COSObjectInputStream cosObjectInputStream = object.getObjectContent()) {
            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filePath);
            byte[] bytes = IoUtil.readBytes(cosObjectInputStream);
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        }
    }
}
